from flask import Blueprint, render_template, redirect, request, session
from model import *
from news.checklogin import checklogin

user = Blueprint ("user", __name__)

"""=============================================首页================================================================="""


@user.route ("/")
@checklogin
def home ():
    users = User.query.all ()
    return render_template ("user/user.html", users = users)


'''==============================================个人资料============================================================='''


@checklogin
@user.route ("/base/")
def base ():
    users = User.query.all ()
    return render_template ("user/user_base_info.html", users = users)


'''==============================================修改头像============================================================='''


@user.route ("/photo", methods = ["GET", "POST"])
def photo ():
    uid = session.get ("uid")
    if not uid:
        return redirect ("/login")
    users = User.query.get (uid)

    if request.method == "GET":
        return render_template ("user/user_pic_info.html", users = users)
    else:
        photo = request.files.get ("photo")
        print (photo)
        photo.save ("static/upload/" + photo.filename)
        users.photo = "/static/upload/" + photo.filename
        db.session.commit ()
        return {"msg": "修改成功"}


'''==============================================新闻发布============================================================='''


@user.route ("/addnews", methods = ["GET", "POST"])
def addnews ():
    if request.method == "GET":
        cates = Cate.query.all ()
        return render_template ("user/user_news_release.html", cates = cates)
    else:
        title = request.form.get ("title")
        cate = request.form.get ("cate")
        pic = request.files.get ("pic")
        cent = request.form.get ("cent")
        print(cent)
        pic.save("static/upload/" + pic.filename)
        news = News (title = title, cate_id = cate, pic = "/static/upload/" + pic.filename, content = cent)
        db.session.add (news)
        db.session.commit ()
        return redirect ("/user/newlist")


'''==============================================新闻发布============================================================='''


@user.route ("/newlist")
def newlist ():
    newslist = News.query.all ()
    return render_template ("user/user_news_list.html", newslist = newslist)
